import { AuthResponse, RegisterData, LoginData, User, UpdateUserData, ChangePasswordData } from '@/types/api';
import axios from 'axios';
import { globalLoading } from '@/components/common/GlobalLoading';
import { message } from 'antd';

// API基础URL，用于API请求
const API_BASE_PATH = '/api';
// 媒体文件基础URL，用于视频和音频文件的访问
export const MEDIA_BASE_URL = 'http://82.157.28.20:19900';

export const API_BASE_URL = API_BASE_PATH;

export const apiClient = axios.create({
    baseURL: API_BASE_URL,
    headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
    },
});

export const getToken = (): string | null => {
    return localStorage.getItem('auth_token');
};

export const setToken = (token: string): void => {
    localStorage.setItem('auth_token', token);
};

export const clearToken = (): void => {
    localStorage.removeItem('auth_token');
};

export const isAuthenticated = (): boolean => {
    return !!getToken();
};

// 判断是否需要显示loading效果的函数
const shouldDisplayLoading = (url: string): boolean => {
    // 不需要显示loading的接口正则表达式模式（只匹配新版本API）
    const noLoadingPatterns = [
        // 新版本轨道操作
        /tracks\/(delete|create)\/[^\/]+\//, // /api/tracks/delete/{draft_id}/ 或 /api/tracks/create/{draft_id}/
        // 新版本片段操作
        /drafts\/[^\/]+\/tracks\/[^\/]+\/segments\//, // /api/drafts/{draft_id}/tracks/{track_id}/segments/
        /drafts\/[^\/]+\/tracks\/[^\/]+\/segments\/[^\/]+\//, // /api/drafts/{draft_id}/tracks/{track_id}/segments/{segment_id}/
        /drafts\/[^\/]+\/tracks\/[^\/]+\/segments\/batch\//, // /api/drafts/{draft_id}/tracks/{track_id}/segments/batch/
        /draft\/detail/,
        // 支付状态查询
        /payment\/orders\/[^\/]+\/status\//, // /api/payment/orders/{out_trade_no}/status/
    ];
    // 检查URL是否匹配不需要loading的模式
    return !noLoadingPatterns.some((pattern) => pattern.test(url));
};

apiClient.interceptors.request.use((config) => {
    const token = getToken();
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }

    // 判断是否需要显示loading效果
    const shouldShowLoading = shouldDisplayLoading(config.url || '');
    if (shouldShowLoading) {
        globalLoading.show();
    }

    return config;
});

apiClient.interceptors.response.use(
    (response) => {
        // 判断是否需要关闭loading效果
        const shouldShowLoading = shouldDisplayLoading(response.config.url || '');
        if (shouldShowLoading) {
            globalLoading.hide();
        }

        // 这里进行判断了 如果状态是200 直接返回data
        // 所以后续在组件中调用任何方法，只需要判断res是否存在即可
        if (response.status === 200 && response.data.code === 200) {
            return response.data;
        } else {
            message.error(response?.data?.message || '请求失败');
        }
        return response;
    },
    (error) => {
        if (error.response?.status === 401) {
            clearToken();
        }
        if (error.response?.status !== 200) {
            message.error(error.response?.data?.message || '请求失败');
        }

        // 判断是否需要关闭loading效果
        const shouldShowLoading = shouldDisplayLoading(error.config?.url || '');
        if (shouldShowLoading) {
            globalLoading.hide();
        }

        return Promise.reject(error);
    }
);

export const login = async (loginData: LoginData): Promise<AuthResponse> => {
    const { data: result } = await apiClient.post<AuthResponse>(`/auth/login/`, loginData);
    if (result.access_token) {
        setToken(result.access_token as string);
    }
    return result;
};

export const register = async (registerData: RegisterData): Promise<AuthResponse> => {
    const { data: result } = await apiClient.post<AuthResponse>(`/auth/register/`, registerData);
    if (result.access_token) {
        setToken(result.access_token);
    }
    return result;
};

export const logout = async (): Promise<void> => {
    try {
        await apiClient.post(`/auth/logout/`);
    } catch (error) {
        console.error('登出错误:', error);
    } finally {
        clearToken();
    }
};

export const getCurrentUser = async (): Promise<any> => {
    const { data: userData } = await apiClient.get<{ data: User }>(`/auth/me`);
    return userData;
};

export const updateProfile = async (profileData: UpdateUserData): Promise<any> => {
    const { data } = await apiClient.put<{ data: User }>(`/auth/profile`, profileData);
    return data;
};

export const changePassword = async (passwordData: ChangePasswordData): Promise<any> => {
    const { data } = await apiClient.post(`/auth/change-password`, passwordData);
    return data;
};

// ================== Points ==================
export interface PointsHistoryItem {
    id: number;
    type: 'increase' | 'decrease';
    amount: number;
    reason: string;
    draft_id: string | null;
    balance_after: number;
    created_at: string; // ISO 8601
}

export interface PointsMeData {
    balance: number;
    used_points: number;
    gained_points: number;
    history: PointsHistoryItem[];
}

export const getMyPoints = async (): Promise<PointsMeData> => {
    const resp: any = await apiClient.get<{ data: PointsMeData }>(`/points/me`);
    const points: PointsMeData = resp?.data?.data ?? resp?.data ?? resp;
    if (!points || typeof points.balance !== 'number') {
        throw new Error('Invalid points response');
    }
    return points;
};

// 支付相关接口
export interface PaymentOrderData {
    order_id: string;
    out_trade_no: string;
    amount: number;
    amount_yuan: number;
    description: string;
    payment_type: string;
    status: string;
    code_url: string;
    prepay_id: string;
    created_at: string;
    expired_at: string | null;
}

export interface CreatePaymentOrderRequest {
    amount: number; // 支付金额（分）
    description?: string; // 商品描述
}

export const createPaymentOrder = async (data: CreatePaymentOrderRequest): Promise<PaymentOrderData> => {
    const resp: any = await apiClient.post<{ data: PaymentOrderData }>(`/payment/orders/`, data);
    return resp?.data?.data ?? resp?.data ?? resp;
};

// 微信登录相关接口
export interface WechatLoginResponse {
    success: boolean;
    message: string;
    data: {
        user: {
            id: number;
            username: string;
            email: string;
            profile: {
                wechat_openid: string;
                wechat_nickname: string;
                wechat_avatar: string;
            };
        };
        tokens: {
            access: string;
            refresh: string;
        };
    };
}

export interface WechatStatusResponse {
    success: boolean;
    message: string;
    data: {
        is_registered: boolean;
        user?: {
            id: number;
            username: string;
            profile: {
                wechat_openid: string;
                wechat_nickname: string;
            };
        };
    };
}

// 获取微信授权URL
export const getWechatAuthUrl = (redirectUri: string, scope: string = 'snsapi_userinfo'): string => {
    const baseUrl = API_BASE_URL;
    return `${baseUrl}/auth/wechat/authorize/?redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scope}`;
};

// 检查微信登录状态
export const checkWechatStatus = async (openid: string): Promise<WechatStatusResponse> => {
    const resp: any = await apiClient.get<WechatStatusResponse>(`/auth/wechat/status/?openid=${openid}`);
    return resp?.data ?? resp;
};

// 获取微信JS API票据
export interface WechatJsApiTicketResponse {
    appId: string;
    timestamp: number;
    nonceStr: string;
    signature: string;
    url: string;
    state?: string; // 可选字段
}

export const getWechatJsApiTicket = async (url: string): Promise<WechatJsApiTicketResponse> => {
    const resp: any = await apiClient.get<WechatJsApiTicketResponse>(`/auth/wechat/jsapi-ticket/?url=${encodeURIComponent(url)}`);
    return resp?.data ?? resp;
};

// 支付状态查询响应类型
export interface PaymentStatusResponse {
    success: boolean;
    code: number;
    message: string;
    data: {
        out_trade_no: string;
        status: 'SUCCESS' | 'PENDING' | 'FAILED' | 'CANCELLED';
        status_display: string;
        transaction_id?: string;
        paid_at?: string;
    } | null;
}

// 查询支付状态
export const queryPaymentStatus = async (outTradeNo: string): Promise<any> => {
    const resp: any = await apiClient.get<PaymentStatusResponse>(`/payment/orders/${outTradeNo}/status/`);
    return resp?.data ?? resp;
};

// 下载草稿脚本文件
export const downloadDraftScriptFile = async (draftId: string): Promise<void> => {
    const token = getToken();
    if (!token) {
        throw new Error('未找到认证令牌');
    }

    try {
        const response = await fetch(`${API_BASE_URL}/draft/script-file/${draftId}/`, {
            method: 'GET',
            headers: {
                Authorization: `Bearer ${token}`,
                Accept: 'application/json',
            },
        });

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            throw new Error(errorData.message || `下载失败: ${response.status}`);
        }

        // 获取文件名
        const contentDisposition = response.headers.get('Content-Disposition');
        let filename = `draft_${draftId}_script_file.json`;

        if (contentDisposition) {
            const filenameMatch = contentDisposition.match(/filename="(.+)"/);
            if (filenameMatch) {
                filename = filenameMatch[1];
            }
        }

        // 创建下载链接
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    } catch (error) {
        console.error('下载草稿文件失败:', error);
        throw error;
    }
};

// 购买模板接口
export interface PurchaseTemplateRequest {
    template_id: string;
}

export interface PurchaseTemplateResponse {
    success: boolean;
    code: number;
    message: string;
    data: {
        draft: any;
        template: any;
    };
}

export const purchaseTemplate = async (data: PurchaseTemplateRequest): Promise<PurchaseTemplateResponse> => {
    const resp: any = await apiClient.post<PurchaseTemplateResponse>(`/draft/purchase-template/`, data);
    return resp?.data ?? resp;
};

// 生成访问令牌接口
export interface GenerateAccessKeyResponse {
    success: boolean;
    code: number;
    message: string;
    data: {
        user_id: number;
        username: string;
        access_key: string;
        generated_at: string;
    };
}

export const generateAccessKey = async (): Promise<any> => {
    return apiClient.post<GenerateAccessKeyResponse>(`/auth/generate-access-key`);
};
